package com.bnzj.cloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName UserInfoFilter
 * @Description TODO
 * @Author
 * @Date 2019/9/11
 * @Version V1.0
 **/
@Component
public class UserInfoFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return ReactiveSecurityContextHolder.getContext()
                .map(SecurityContext::getAuthentication)
                .map(authentication -> {
                    String userName = null;
                    String headerName = "X-USER-NAME";
                    if(authentication instanceof JwtAuthenticationToken){
                        userName = ((Jwt)authentication.getCredentials()).getClaims().get("user_name").toString();
                    }else if(authentication instanceof UsernamePasswordAuthenticationToken){
                        userName = (String) authentication.getPrincipal();
                        headerName = (String)authentication.getCredentials();
                    }
                    ServerHttpRequest host = exchange.getRequest().mutate()
                            .header(headerName, userName)
                            .build();
                    ServerWebExchange build = exchange.mutate().request(host).build();
                    return build;
                }).flatMap(chain::filter)
                .switchIfEmpty(chain.filter(exchange));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
